<template>
  <div class="app-container">
    <div class="query-box">
      <el-row :gutter="24">
        <el-col :span="4" :xs="24">
          <el-button type="primary" plain icon="el-icon-circle-plus-outline" size="small" class="mr10"
                     @click="handleAdd()">新增
          </el-button>
          <el-button type="danger" plain icon="el-icon-delete" size="small" class="mr10" @click="handleDelBatch">删除
          </el-button>
        </el-col>
        <el-col :span="20" :xs="24" align="right">
          <el-form :model="query" ref="queryForm" :inline="true" label-width="70px">
            <el-form-item label="用户名：">
              <el-input
                v-model="query.username"
                clearable
                size="small"
              />
            </el-form-item>
            <el-form-item label="名字：">
              <el-input
                v-model="query.name"
                clearable
                size="small"
              />
            </el-form-item>
            <el-form-item label="状态：" prop="result">
              <el-radio-group v-model="query.status">
                <el-radio label="ENABLE" value="ENABLE">启用</el-radio>
                <el-radio label="DISABLE" value="DISABLE">停用</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleSearch">搜索</el-button>
          </el-form>
        </el-col>
      </el-row>
    </div>

    <el-table @selection-change="clickRow" v-loading="loading" :data="list" element-loading-text="Loading" border fit
              class="table">
      <el-table-column type="selection"></el-table-column>
       
      <el-table-column align="center" label="用户名" prop="username"></el-table-column>
      <el-table-column align="center" label="名字" prop="name"></el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value=1 :inactive-value=2 active-color="#409EFF"
                     inactive-color="#B9B9B9" @change="changeStatus(scope.$index, scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark"></el-table-column>
      <el-table-column align="center" prop="createTime" label="添加时间">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime | datetimeFormat}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="170"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleAdd(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDel(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination background layout="total, prev, pager, next" :current-page="query.pageNo"
                     :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
    </div>

    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="名字" prop="name">
              <el-input v-model="form.name"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" :disabled="form.username"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="说明" prop="remark">
              <el-input type="textarea" :rows="5" v-model="form.remark"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="isSaveBtnDisabled">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {accounts, saveAccount, delAccount, delAccountBatch, updateAccountStatus} from "@/api/api"

  export default {
    name: "Account",
    data() {
      return {
        isSaveBtnDisabled: false,
        // 遮罩层
        loading: true,
        list: [],
        selectedIds: [],
        pageTotal: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        query: {
          username: '',
          name: '',
          pageNo: 0,
          pageSize: 10
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [{required: true, message: "名字不能为空", trigger: "blur"}],
          username: [{required: true, message: "用户名不能为空", trigger: "blur"},
            {min: 2, max: 20, message: '用户名只能输入2~20个字符', trigger: 'blur'}],
          password: [{required: true, message: "密码不能为空", trigger: "blur"},
            {min: 6, max: 30, message: "用户名只能输入6~30个字符", trigger: "blur"}],
        }
      };
    },
    created() {
      this.getList();
    },
    methods: {
      clickRow(row) {
        this.selectedIds = []
        let that = this
        row.forEach(function (val, index) {
          that.selectedIds.push(val.id)
        })
      },
      getList() {
        this.loading = true;
        accounts(this.query).then(response => {
          this.list = response.data.records;
          this.query.pageNo = response.data.current;
          this.pageTotal = response.data.total;
          this.loading = false
        })
      },
      // 取消按钮
      cancel() {
        this.open = false
      },
      /** 搜索按钮操作 */
      handleSearch() {
        this.getList();
      },
      /** 重置按钮操作 */
      resetSearch() {
        this.query = {}
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.open = true
        this.form = row || {}
        this.form.password = ""
      },
      /** 提交按钮 */
      submitForm: function () {
        this.isSaveBtnDisabled = true
        this.$refs["form"].validate(valid => {
          if (!valid) {
            this.isSaveBtnDisabled = false
            return
          }

          let that = this
          saveAccount(this.form).then(response => {
            that.msgSuccess((this.form.id ? "修改" : "新增") + "账号成功")
            that.open = false
            that.getList()
            that.isSaveBtnDisabled = false
          }).catch(() => {
            this.isSaveBtnDisabled = false
          });
        });
      },
      /** 删除按钮操作 */
      handleDel(row) {
        let that = this
        this.$confirm('是否确认删除【' + row.username + '】?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          delAccount(row.id).then(() => {
            that.getList();
            that.msgSuccess("删除成功");
          })
        })
      },
      handleDelBatch() {
        let that = this
        this.$confirm('是否确认删除这些记录?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          delAccountBatch({ids: that.selectedIds}).then(() => {
            that.resetSearch()
            that.getList();
            that.msgSuccess("删除成功");
          })
        })
      },
      // 分页导航
      handlePageChange(val) {
        this.query.pageNo = val
        this.getList(this.query)
      },
      changeStatus(index, row) {
        updateAccountStatus(row.id, row.status == 1 ? "enable" : "disable").catch(res => {
          this.list[index].status = row.status == 1 ? 2 : 1
        });
      }
    }
  };
</script>
